#include "input.h"
#include "../device/device.h"
#include "../msg/msg.h"

#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/time.h>
#include <linux/input.h>
#include <stdio.h>

#include <types.h>
#include <macro.h>

int input::xold		= 0;
int input::yold		= 0;
int input::xnew		= 0;
int input::ynew		= 0;
enum SYSTEM_MSG input::key = BTN_NULL;
int input::fd		= -1;

input::input(){};
input::~input(){};
int input::init(){
	int ret=0;
        //fd=open(INPUT_DEVICE,O_RDONLY);
        fd=open("/dev/input/event2",O_RDONLY);
        if(fd<0){
                //msgbox.....
                return -1;
        }
	return ret;
};

int input::exit(){
	int ret=0;
	if(fd>=0)
		ret=close(fd);
	return ret;
};

void * input::receive(void *p){
	//char buf[6];
	struct input_event t;
	int ret=-1;

	fd_set fds;
	struct timeval timeout={1,0}; 

	//memset(buf,0,6);
	key=BTN_NULL;
	while(key!=BTN_EXIT){
		FD_ZERO(&fds);
		FD_SET(fd,&fds);
		ret=select(fd+1,&fds,NULL,NULL,&timeout);
		if(ret){
			read(fd, &t, sizeof(t));
			if(t.type==EV_KEY)
			if(/*t.value==0||*/t.value==1)
			switch(t.code){
				case ESC:
					key=BTN_EXIT;
					device::message(new msg(xold,yold,xnew,ynew,key));
				break;
				case UP:
					key=BTN_UP;
					device::message(new msg(xold,yold,xnew,ynew,key));
				break;
				case DOWN:
					key=BTN_DOWN;
					device::message(new msg(xold,yold,xnew,ynew,key));
				break;
				case LEFT:
					key=BTN_NEXT;
					device::message(new msg(xold,yold,xnew,ynew,key));
				break;
				case RIGHT:
					key=BTN_PRV;
					device::message(new msg(xold,yold,xnew,ynew,key));
				break;
				case ENTER:
					key=BTN_OK;
					device::message(new msg(xold,yold,xnew,ynew,key));
				break;
				case DOCKUI:
					key=BTN_UI;
					device::message(new msg(xold,yold,xnew,ynew,key));
				break;


				default:

				break;
			}
		}
	}

};
